<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>报销补帖</el-breadcrumb-item>
      <el-breadcrumb-item>补贴管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>外聘人员费申请</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="日期" prop="outdate">
        <el-date-picker clearable
                        v-model="searchFormModel.outdate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审批状态" prop="state">
        <el-select v-model="searchFormModel.state" placeholder="请选择审批状态" clearable style="width: 200px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="已拒绝" value="0"></el-option>
          <el-option label="已通过" value="1"></el-option>
          <el-option label="已驳回" value="2"></el-option>
          <el-option label="已撤销" value="3"></el-option>
          <el-option label="审批中" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="searchOnSubmit">查询</el-button>
        <el-button style="background-color: pink" @click="dialogAddState=true">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%">
      <el-table-column label="员工姓名" align="center" prop="name" />
      <el-table-column label="日期" align="center" prop="outdate" width="180"/>
      <el-table-column label="费用" align="center" prop="cost" />
      <!--      <el-table-column label="签领人签字" align="center" prop="isSign" />-->
      <el-table-column label="签领人签字" align="center" prop="is_sign"/>
      <el-table-column label="费用单号" align="center" prop="cost_number" />
      <el-table-column label="总费用" align="center" prop="cost_sum" />
      <el-table-column label="审批状态" align="center" prop="state">
        <template #default="scope">
          <span v-if="scope.row.state===0"><el-tag type="danger">已拒绝</el-tag></span>
          <span v-if="scope.row.state===1"><el-tag type="success">已通过</el-tag></span>
          <span v-if="scope.row.state===2"><el-tag type="danger">已驳回</el-tag></span>
          <span v-if="scope.row.state===3"><el-tag type="danger">已撤销</el-tag></span>
          <span v-if="scope.row.state===4"> <el-tag type="warning">审批中</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small"
                     :disabled="scope.row.state === 3 || scope.row.state === 1 || scope.row.state === 0 ||  scope.row.state === 4"
                     @click="tableEditHandler(scope.$index, scope.row) ">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              :disabled="scope.row.state === 3 || scope.row.state === 1 || scope.row.state === 0 ||  scope.row.state === 4"
              @click="tableDeleteHandler(scope.row.id)">
            <el-icon><Switch /></el-icon>撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3,5]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--  编辑模态框-->
  <el-dialog v-model="dialogEditState" title="修改外聘人员费申请" width="700">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="formEdit.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="日期" prop="outdate">
          <el-date-picker clearable
                          v-model="formEdit.outdate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用" prop="cost">
          <el-input v-model="formEdit.cost" placeholder="请输入费用" />
        </el-form-item>
        <el-form-item label="签领人签字" prop="is_sign">
          <el-select v-model="formEdit.is_sign" placeholder="请选择是否签字" clearable style="width: 200px;">
            <el-option label="未签字" value="未签字"></el-option>
            <el-option label="已签字" value="已签字"></el-option>
          </el-select>
<!--          <el-input v-model="formEdit.is_sign" placeholder="请输入签领人签字" />-->
        </el-form-item>
        <el-form-item label="费用单号" prop="cost_number">
          <el-input v-model="formEdit.cost_number" placeholder="请输入费用单号" />
        </el-form-item>
        <el-form-item label="总费用" prop="cost_sum">
          <el-input v-model="formEdit.cost_sum" placeholder="请输入总费用" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >更新</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加模态框 -->
  <el-dialog v-model="dialogAddState" title="添加外聘人员费申请申请" width="680">
    <div>
      <el-form ref="formAddRef" :model="formAdd" label-width="120px" :rules="rules">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="formAdd.name" placeholder="请输入员工姓名" maxlength="10"/>
        </el-form-item>
        <el-form-item label="日期" prop="outdate">
          <el-date-picker clearable
                          v-model="formAdd.outdate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          @change="formDate1"
                          placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用" prop="cost">
          <el-input v-model="formAdd.cost" placeholder="请输入费用" maxlength="10"/>
        </el-form-item>
        <el-form-item label="签领人签字" prop="is_sign">
          <el-select v-model="formAdd.is_sign" placeholder="请选择是否签字" clearable >
            <el-option label="已签字" value="已签字"></el-option>
            <el-option label="未签字" value="未签字"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用单号" prop="cost_number">
          <el-input v-model="formAdd.cost_number" placeholder="请输入费用单号" maxlength="15"/>
        </el-form-item>
        <el-form-item label="总费用" prop="cost_sum">
          <el-input v-model="formAdd.cost_sum" placeholder="请输入总费用" maxlength="10"/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary" @click="submitRegisterForm">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!--审批模态框-->
  <el-dialog v-model="dialogCheckState" title="请选择审批状态" width="700" >
    <div>
      <el-form ref="formCheckRef" :model="formCheck" label-width="120px">
        <el-form-item prop="state" label="审批状态">
          <template #default="scope">
            <div>
              <el-radio-group v-model="formCheck.state" :disabled="formCheck.state === 1 || formCheck.state === 0 || formCheck.state === 3">
                <el-radio value="1" size="large" border >通过</el-radio>
                <el-radio value="0" size="large" border >拒绝</el-radio>
                <el-radio value="2" size="large" border :disabled="formCheck.state === 2">驳回</el-radio>
              </el-radio-group>
            </div>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogCheckOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogCheckOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ArrowRight} from "@element-plus/icons-vue";
import {Delete, DocumentChecked, Edit, Plus, Switch} from "@element-plus/icons";
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/reimburse";
import {ElMessage, ElMessageBox, UploadProps, UploadUserFile} from "element-plus";
import axios from "axios";


onMounted(()=>{
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('loginUser')

  userInfo.username = JSON.parse(userstr).username
  getOutmemberApply();
})

//分页
const currentPage = ref(1)
const pageSize = ref(3)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const userInfo = reactive({
  'username' :null
})
const  blogInfo=ref([])
// 表格显示内容
const getOutmemberApply = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    number: userInfo.username
    // 初始时不包含ID参数
  };
  // 如果日期不为空，则添加到查询参数中
  if (searchFormModel.outdate && searchFormModel.outdate.trim() !== '') {
    params.outdate = searchFormModel.outdate.trim();
  }
  // 如果审批状态不为空，则添加到查询参数中
  if (searchFormModel.state && searchFormModel.state.trim() !== '') {
    params.state = searchFormModel.state.trim();
  }
  request({
    url: '/outmemberApply/selectByNum',
    method: 'get',
    params,
  }).then((req) => {
    console.log(req)
    if (200 == req.data.errorCode) {
      blogInfo.value = req.data.data.records.map(item => ({
        ...item,
      }));
      totals.value = req.data.data.total;
    }
  })
}
const handleCurrentChange = (page) => {
  currentPage.value = page
  getOutmemberApply()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  getOutmemberApply()
}

//搜索
const searchFormRef=ref()
const searchFormModel=reactive({
  id:'',
  number:userInfo.username,
  outdate:'',
  state:''
})


const searchOnSubmit=()=>{
  getOutmemberApply()
}

const rules=reactive({
  name: [
    { required: true, message: "员工姓名不能为空", trigger: "blur"}
  ],
  outdate: [
    { required: true, message: "日期不能为空", trigger: "blur" }
  ],
  cost: [
    { required: true, message: "费用不能为空", trigger: "blur"}
  ],
  is_sign: [
    { required: true, message: "是否签字不能为空", trigger: "change" }
  ],
  cost_number: [
    { required: true, message: "费用单号不能为空", trigger: "blur" }
  ],
  cost_sum: [
    { required: true, message: "总费用不能为空", trigger: "blur" }
  ]
})
///////////////////编辑/////////////////////////
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.id = rowData.id
  formEdit.number = rowData.number
  formEdit.name = rowData.name
  formEdit.outdate = rowData.outdate
  formEdit.cost = rowData.cost
  formEdit.is_sign = rowData.is_sign
  formEdit.cost_number = rowData.cost_number
  formEdit.cost_sum = rowData.cost_sum
  formEdit.state = rowData.state


  dialogEditState.value = true
}
// 新增表单引用
const formEditRef = ref()
const dialogEditState = ref(false)
const dialogEditOnSubmit = () => {
  // 数据提交到服务器
  // 服务器端返回成功 ：清空表单，关闭对话框，更新表格内容
  request({
    method:'PUT',
    url:'/outmemberApply/update',
    data:JSON.stringify(formEdit),
    headers: {'content-type': 'application/json;charset=UTF-8'}
  }).then(req=>{
    ElMessage({
      type:'success',
      message:req.data.msg
    })
    if (200==req.data.errorCode){
      getOutmemberApply()
    }
  })
  dialogEditState.value = false
}
// 新增表单初始化数据
const formEditData = {
  id:'',
  name:'',
  outdate:'',
  cost:'',
  is_sign:'',
  cost_number:'',
  cost_sum:'',
  state:''
}
const dialogEditOnReset = () => {
  formEdit.name=''
  formEdit.outdate=''
  formEdit.cost=''
  formEdit.is_sign=''
  formEdit.cost_number=''
  formEdit.cost_sum=''
  formEdit.state=''
  // 关闭对话框
  dialogEditState.value=false;
}
// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})
///////////////////添加/////////////////////////
const dialogAddState = ref(false);
const formAddData = {
  number:'',
  name:'',
  outdate:'',
  cost:'',
  is_sign:'',
  cost_number:'',
  cost_sum:'',
  state:''
};
const formAdd = reactive({...formAddData});
const addressFormRef = ref(null); // 创建一个ref引用form
// 时间
const formDate1=(value)=> {
  if (!value) {
    // 如果日期时间选择器的值为空，则不进行格式化
    formAdd.outdate = '';
    return;
  }
  // 将日期时间字符串转换为Date对象
  const date = new Date(value);
  // 获取年、月、日、小时、分钟和秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  // 组合成所需的格式
  formAdd.outdate = `${year}-${month}-${day} `;
}

// 提交表单
function submitRegisterForm (){
  if (formAddData.number == '' && formAddData.number.trim() == '') {
    formAdd.number = userInfo.username;
  }
  request({
    method:'post',
    url:'/outmemberApply/add',
    params:formAdd,
    /*   headers:{'content-type' : "application/json;charset=UTF-8"},*/
    contentType: 'application/json;charset=UTF-8'
  }).then(req=>{
    ElMessage({
      type:'info',
      message:req.data.msg
    })
    if (200 == req.data.errorCode){
      Object.assign(formAdd,formAddData)
      getOutmemberApply()
    }
  })
  dialogAddState.value=false;
}
const dialogAddOnReset = () => {
  formAdd.name=''
  formAdd.outdate=''
  formAdd.cost=''
  formAdd.is_sign=''
  formAdd.cost_sum=''
  formAdd.cost_number=''
  formAdd.state=''
  // 关闭对话框
  dialogAddState.value=false;
}

//撤销
const tableDeleteHandler = (id) => {
  request({
    url: `/outmemberApply/updateC?id=${id}`, // 如果后端通过 URL 参数接收 ID
    method: 'put',
    // 如果后端期望 ID 在请求体中，可以这样设置
    data: JSON.stringify({...formEdit, id }),
    headers: {'content-type': "application/json;charset=UTF-8"}
  }).then(req => {
    ElMessage({
      type: 'success',
      message: req.data.msg
    });
    if (200 === req.data.errorCode) {
     getOutmemberApply()
    }
  });
  dialogEditState.value = false;
};
</script>
<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
</style>